package main

import (
	"fmt"
	"github.com/golang/protobuf/proto"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
	"Gocode/study.com/RPCandgRPC/grpc/Token/message"
)

//token认证
type TokenAuthentication struct {
	AppKey    string
	AppSecret string
}

//实现PerRPCCredentials接口方法
//组织token信息
func (ta *TokenAuthentication) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"appid":  ta.AppKey,
		"appkey": ta.AppSecret,
	}, nil
}


//func (ta *TokenAuthentication) GetRequestMetaData(ctx context.Context, uri ...string) (map[string]string, error) {
//	return map[string]string{
//		"appid":  ta.AppKey,
//		"appkey": ta.AppSecret,
//	}, nil
//}

//是否基于TLS认证进行安全传输
func (a *TokenAuthentication) RequireTransportSecurity() bool {
	return true
}

func main() {
	//TLS连接
	//第二个参数要和命令行生成密钥时的common name一致
	creds, err := credentials.NewClientTLSFromFile("E:\\Goproject\\src\\learn\\RPCandgRPC\\grpc\\SSLAndTLS\\SSL\\keys\\server.pem", "gogrpc")
	if err != nil {
		//panic(err.Error())
		fmt.Println("credentials.NewClientTLSFromFile error:", err)
		return
	}

	auth := &TokenAuthentication{
		AppKey:    "goToken",
		AppSecret: "goSecret",
	}

	//1、Dail连接（TLS连接）
	conn, err := grpc.Dial(":9000", grpc.WithTransportCredentials(creds), grpc.WithPerRPCCredentials(auth))
	if err != nil {
		panic(err.Error())
	}
	defer conn.Close()

	serviceClient := message.NewGetUserServiceClient(conn)

	names := []string{"小明"}
	//genders := []string{"男", "女"}
	//gender:=models.Gender(0)
	args := &message.UserRequest{
		Name:   names,
		Age:    *proto.Uint32(20),
		Gender: *proto.Int32(0),
	}

	response, err := serviceClient.GetUser(context.Background(), args)
	if err != nil {
		grpclog.Fatal(err.Error())
	}

	fmt.Println(response)
	fmt.Println(response.String())
	fmt.Println(response.GetName())
	fmt.Println(response.GetGender())
}
